#pragma once
#include "log.hpp"
#include "Socket.hpp"
#include <thread>

#define PORT 9000

class HttpServer
{
public:
    HttpServer(uint16_t port = PORT) : _port(port) {}

    void startServer()
    {
        _sock.Socket();
        _sock.Bind(_port);
        _sock.Listen();

        for (;;) {
            string clientIp;
            uint16_t clientPort;
            int sockFd = _sock.Accept(&clientIp, &clientPort);
            log(INFO, "get a new link, fd: %d\n", sockFd);
            thread([=]
            {
                char buf[10240];
                memset(buf, 0, sizeof buf);
                for(;;) {
                    ssize_t n = read(sockFd, buf, sizeof buf);
                    if (n > 0) {
                        buf[n] = 0;
                        cout << buf;
                    } else if (n==0) {
                        cout << "read done\n";
                        break;
                    } else {
                        cout << "read error!\n";
                        break;
                    }
                }   
                close(sockFd);
            }).detach();
        }
    }
private:
    Sock _sock;
    uint16_t _port;
};